<template>
  <div class="app-container">
    <el-card>
      <!-- 试卷基本信息区域 -->
      <div class="paper-info">
        <h1 class="paper-title">{{ paper.paperName }}</h1>
        <div class="paper-metadata">
          <div class="metadata-item">
            <span>学号：</span>
            <span>{{ student.studentId }}</span>
          </div>
          <div class="metadata-item">
            <span>姓名：</span>
            <span>{{ student.studentName }}</span>
          </div>
          <div class="metadata-item">
            <span>题目数：</span>
            <span>{{ allQuestions.length }}题</span>
          </div>
          <div class="metadata-item">
            <span>成绩：</span>
            <span class="score-value" :class="getScoreClass(calculateTotalScore(), paper.totalScore)">
              {{ calculateTotalScore().toFixed(1) }}/{{ paper.totalScore }}分
            </span>
          </div>
          
          
        </div>
      </div>

      <!-- 试卷内容区域 -->
      <div class="paper-content" v-loading="loading">
        <!-- 各题型分类显示 -->
        <!-- 单选题 -->
        <div v-if="singleChoiceQuestions.length > 0" class="question-section">
          <div class="section-title">一、单选题（共{{ singleChoiceQuestions.length }}题，共{{ getSectionScore(singleChoiceQuestions) }}分）</div>
          <div v-for="(question, index) in singleChoiceQuestions" :key="question.question_id" 
               class="question-item" :class="{'error-question': !question.is_correct}">
            <div class="question-content">
              <div class="question-title">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-type">[单选题]</span>
                <span class="question-score">({{ question.question_score }}分)</span>
              </div>
              <div class="question-text" v-html="question.question_content"></div>
              <div class="options-container">
                <div class="options-list">
                  <div v-for="(option, optIndex) in parseOptions(question.options)" :key="optIndex" class="option-item">
                    <el-radio v-model="question.student_answer" :label="option.value" disabled class="option-radio">
                      <span class="option-key">{{ option.label }}.</span>
                      <span class="option-content" v-html="option.content"></span>
                    </el-radio>
                  </div>
                </div>
              </div>
            </div>
            <!-- 答案区域 -->
            <div class="answer-area">
              <div class="student-answer">
                <div class="answer-label">学生答案：</div>
                <div class="answer-content">{{ formatStudentAnswer(question) }}</div>
              </div>
              <div class="correct-answer">
                <div class="answer-label">正确答案：</div>
                <div class="answer-content">{{ formatCorrectAnswer(question) }}</div>
              </div>
              <!-- 评分控件 -->
              <div class="score-control">
                <div class="score-label">
                  <span>得分：</span>
                </div>
                <div class="input-group">
                  <el-button size="small" @click="decreaseScore(question)">-</el-button>
                  <el-input 
                    v-model="question.student_score" 
                    size="small" 
                    class="score-input" 
                    type="number"
                    :min="0"
                    :max="question.question_score"
                    :step="0.5"
                    @input="val => validateScoreInput(val, question)"
                    @change="updateScoreStatus(question)"
                    @blur="updateScoreStatus(question)"
                  ></el-input>
                  <el-button size="small" @click="increaseScore(question)">+</el-button>
                </div>
                <el-button 
                  v-if="question.question_type === 4" 
                  size="small" 
                  type="primary" 
                  @click="handleClickAiAssist(question)" 
                  class="ai-assist-btn"
                >AI辅助批阅</el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 多选题 -->
        <div v-if="multiChoiceQuestions.length > 0" class="question-section">
          <div class="section-title">二、多选题（共{{ multiChoiceQuestions.length }}题，共{{ getSectionScore(multiChoiceQuestions) }}分）</div>
          <div v-for="(question, index) in multiChoiceQuestions" :key="question.question_id" 
               class="question-item" :class="{'error-question': !question.is_correct}">
            <div class="question-content">
              <div class="question-title">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-type">[多选题]</span>
                <span class="question-score">({{ question.question_score }}分)</span>
              </div>
              <div class="question-text" v-html="question.question_content"></div>
              <div class="options-container">
                <div class="options-list">
                  <div v-for="(option, optIndex) in parseOptions(question.options)" :key="optIndex" class="option-item">
                    <el-checkbox :checked="isOptionSelected(question, option.value)" disabled class="option-checkbox">
                      <span class="option-key">{{ option.label }}.</span>
                      <span class="option-content" v-html="option.content"></span>
                    </el-checkbox>
                  </div>
                </div>
              </div>
            </div>
            <!-- 答案区域 -->
            <div class="answer-area">
              <div class="student-answer">
                <div class="answer-label">学生答案：</div>
                <div class="answer-content">{{ formatStudentAnswer(question) }}</div>
              </div>
              <div class="correct-answer">
                <div class="answer-label">正确答案：</div>
                <div class="answer-content">{{ formatCorrectAnswer(question) }}</div>
              </div>
              <!-- 评分控件 -->
              <div class="score-control">
                <div class="score-label">
                  <span>得分：</span>
                </div>
                <div class="input-group">
                  <el-button size="small" @click="decreaseScore(question)">-</el-button>
                  <el-input 
                    v-model="question.student_score" 
                    size="small" 
                    class="score-input" 
                    type="number"
                    :min="0"
                    :max="question.question_score"
                    :step="0.5"
                    @input="val => validateScoreInput(val, question)"
                    @change="updateScoreStatus(question)"
                    @blur="updateScoreStatus(question)"
                  ></el-input>
                  <el-button size="small" @click="increaseScore(question)">+</el-button>
                </div>
                <el-button 
                  v-if="question.question_type === 4" 
                  size="small" 
                  type="primary" 
                  @click="handleClickAiAssist(question)" 
                  class="ai-assist-btn"
                >AI辅助批阅</el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 判断题 -->
        <div v-if="judgmentQuestions.length > 0" class="question-section">
          <div class="section-title">三、判断题（共{{ judgmentQuestions.length }}题，共{{ getSectionScore(judgmentQuestions) }}分）</div>
          <div v-for="(question, index) in judgmentQuestions" :key="question.question_id" 
               class="question-item" :class="{'error-question': !question.is_correct}">
            <div class="question-content">
              <div class="question-title">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-type">[判断题]</span>
                <span class="question-score">({{ question.question_score }}分)</span>
              </div>
              <div class="question-text" v-html="question.question_content"></div>
              <div class="options-container">
                <el-radio-group v-model="question.student_answer" disabled>
                  <el-radio label="1" class="option-radio">
                    <span class="option-key">A.</span>
                    <span class="option-content">正确</span>
                  </el-radio>
                  <el-radio label="0" class="option-radio">
                    <span class="option-key">B.</span>
                    <span class="option-content">错误</span>
                  </el-radio>
                </el-radio-group>
              </div>
            </div>
            <!-- 答案区域 -->
            <div class="answer-area">
              <div class="student-answer">
                <div class="answer-label">学生答案：</div>
                <div class="answer-content">{{ formatJudgmentAnswer(question.student_answer) }}</div>
              </div>
              <div class="correct-answer">
                <div class="answer-label">正确答案：</div>
                <div class="answer-content">{{ formatJudgmentAnswer(question.question_answer) }}</div>
              </div>
              <!-- 评分控件 -->
              <div class="score-control">
                <div class="score-label">
                  <span>得分：</span>
                </div>
                <div class="input-group">
                  <el-button size="small" @click="decreaseScore(question)">-</el-button>
                  <el-input 
                    v-model="question.student_score" 
                    size="small" 
                    class="score-input" 
                    type="number"
                    :min="0"
                    :max="question.question_score"
                    :step="0.5"
                    @input="val => validateScoreInput(val, question)"
                    @change="updateScoreStatus(question)"
                    @blur="updateScoreStatus(question)"
                  ></el-input>
                  <el-button size="small" @click="increaseScore(question)">+</el-button>
                </div>
                <el-button 
                  v-if="question.question_type === 4" 
                  size="small" 
                  type="primary" 
                  @click="handleClickAiAssist(question)" 
                  class="ai-assist-btn"
                >AI辅助批阅</el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 填空题 -->
        <div v-if="fillBlankQuestions.length > 0" class="question-section">
          <div class="section-title">四、填空题（共{{ fillBlankQuestions.length }}题，共{{ getSectionScore(fillBlankQuestions) }}分）</div>
          <div v-for="(question, index) in fillBlankQuestions" :key="question.question_id" 
               class="question-item" :class="{'error-question': !question.is_correct}">
            <div class="question-content">
              <div class="question-title">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-type">[填空题]</span>
                <span class="question-score">({{ question.question_score }}分)</span>
              </div>
              <div class="question-text" v-html="question.question_content"></div>
            </div>
            <!-- 答案区域 -->
            <div class="answer-area">
              <div class="student-answer">
                <div class="answer-label">学生答案：</div>
                <div class="answer-content">{{ formatStudentAnswer(question) }}</div>
              </div>
              <div class="correct-answer">
                <div class="answer-label">正确答案：</div>
                <div class="answer-content mathjax-content" v-html="formatFillAnswer(question.options)"></div>
              </div>
              <!-- 评分控件 -->
              <div class="score-control">
                <div class="score-label">
                  <span>得分：</span>
                </div>
                <div class="input-group">
                  <el-button size="small" @click="decreaseScore(question)">-</el-button>
                  <el-input 
                    v-model="question.student_score" 
                    size="small" 
                    class="score-input" 
                    type="number"
                    :min="0"
                    :max="question.question_score"
                    :step="0.5"
                    @input="val => validateScoreInput(val, question)"
                    @change="updateScoreStatus(question)"
                    @blur="updateScoreStatus(question)"
                  ></el-input>
                  <el-button size="small" @click="increaseScore(question)">+</el-button>
                </div>
                <el-button 
                  v-if="question.question_type === 4" 
                  size="small" 
                  type="primary" 
                  @click="handleClickAiAssist(question)" 
                  class="ai-assist-btn"
                >AI辅助批阅</el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 简答题 -->
        <div v-if="essayQuestions.length > 0" class="question-section">
          <div class="section-title">五、简答题（共{{ essayQuestions.length }}题，共{{ getSectionScore(essayQuestions) }}分）</div>
          <div v-for="(question, index) in essayQuestions" :key="question.question_id" 
               class="question-item" :class="{'error-question': !question.is_correct}">
            <div class="question-content">
              <div class="question-title">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-type">[简答题]</span>
                <span class="question-score">({{ question.question_score }}分)</span>
              </div>
              <div class="question-text" v-html="question.question_content"></div>
            </div>
            <!-- 答案区域 -->
            <div class="answer-area">
              <div class="student-answer">
                <div class="answer-label">学生答案：</div>
                <div class="answer-content" v-html="question.student_answer"></div>
              </div>
              <div class="correct-answer">
                <div class="answer-label">参考答案：</div>
                <div class="answer-content" v-html="question.question_answer"></div>
              </div>
              <!-- 评分控件 -->
              <div class="score-control">
                <div class="score-label">
                  <span>得分：</span>
                </div>
                <div class="input-group">
                  <el-button size="small" @click="decreaseScore(question)">-</el-button>
                  <el-input 
                    v-model="question.student_score" 
                    size="small" 
                    class="score-input" 
                    type="number"
                    :min="0"
                    :max="question.question_score"
                    :step="0.5"
                    @input="val => validateScoreInput(val, question)"
                    @change="updateScoreStatus(question)"
                    @blur="updateScoreStatus(question)"
                  ></el-input>
                  <el-button size="small" @click="increaseScore(question)">+</el-button>
                </div>
                <el-button 
                  v-if="question.question_type === 4" 
                  size="small" 
                  type="primary" 
                  @click="handleClickAiAssist(question)" 
                  class="ai-assist-btn"
                >AI辅助批阅</el-button>
              </div>
            </div>
            <!-- AI辅助批阅结果 -->
            <div v-if="question.aiMarkResult" class="ai-mark-result">
              <div class="ai-mark-title">AI批阅结果</div>
              <div class="ai-mark-content" v-html="formatAIResponse(question.aiMarkResult.content)"></div>
              <div class="ai-mark-actions">
                <span class="ai-score-label">AI建议得分：</span>
                <span class="ai-score-value">{{ question.aiMarkResult.suggestedScore.toFixed(1) }}分</span>
                <el-button size="small" type="success" @click="applyAIScore(question)">
                  应用AI得分
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 评语 -->
      <div class="remark-area">
        <div class="remark-label">评语：</div>
        <QuillEditor
          v-model:content="remark"
          content-type="html"
          theme="snow"
          toolbar="full"
          :options="editorOptions"
        />
      </div>
      
      <!-- 提交按钮 -->
      <div class="submit-area">
        <el-button type="primary" @click="submitMark" :loading="loading">提交批阅</el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-card>

    <!-- 添加AI辅助批阅对话框 -->
    <el-dialog
      title="AI辅助批阅"
      v-model="aiAssistDialogVisible"
      width="65%"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div class="ai-assist-dialog">
        <div class="ai-result-container" v-loading="aiLoading">
          <div v-if="currentQuestion && currentQuestion.aiMarkResult" class="ai-result-content">
            <div class="ai-analysis">
              <h3>AI分析评价</h3>
              <div v-html="formatAIResponse(currentQuestion.aiMarkResult.content)" class="ai-analysis-content"></div>
            </div>
            <div class="ai-score" v-if="currentQuestion.aiMarkResult.suggestedScore !== undefined">
              <h3>AI建议得分</h3>
              <div class="ai-score-value">{{ currentQuestion.aiMarkResult.suggestedScore }} 分</div>
              <el-button type="primary" size="small" @click="applyAIScore(currentQuestion)" :disabled="aiLoading">
                应用AI得分
              </el-button>
            </div>
          </div>
          <div v-else-if="!aiLoading" class="ai-empty-state">
            <el-empty description='请点击"AI辅助批阅"按钮开始分析'></el-empty>
          </div>
        </div>

        <div class="ai-chat-container">
          <div class="ai-chat-history" ref="chatHistoryRef">
            <div v-for="(message, index) in aiChatHistory" :key="index" :class="['ai-chat-message', message.role]">
              <div class="ai-chat-content">
                <div class="ai-chat-text" v-html="message.content"></div>
              </div>
            </div>
          </div>
          <div class="ai-chat-input">
            <el-input
              v-model="aiChatInput"
              type="textarea"
              :rows="2"
              placeholder="输入您的问题或指令..."
              @keydown.enter.ctrl.prevent="sendChatMessage"
            ></el-input>
            <div class="ai-chat-actions">
              <el-tooltip content="点击开始AI辅助批阅" placement="top">
                <el-button 
                  type="primary" 
                  :loading="aiLoading" 
                  @click="aiAssistMark(currentQuestion)"
                  :disabled="!currentQuestion || !currentQuestion.student_answer || !currentQuestion.question_content"
                >AI辅助批阅</el-button>
              </el-tooltip>
              <el-tooltip content="测试AI API连接" placement="top">
                <el-button type="danger" @click="testAIConnection" :loading="apiTestLoading">测试API</el-button>
              </el-tooltip>
              <el-tooltip content="发送聊天消息 (Ctrl+Enter)" placement="top">
                <el-button type="success" @click="sendChatMessage" :disabled="!aiChatInput.trim()">发送</el-button>
              </el-tooltip>
              <el-button @click="aiAssistDialogVisible = false">关闭</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAnswerDetail, markPaper } from '@/api/manage/mark';
import { getPaperForExam } from '@/api/manage/answer';
import { getStudentByNumber } from '@/api/manage/student';
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import { assistMarkSubjectiveQuestion, testAIConnection, chatWithAI } from '@/api/manage/ai';
import { ElMessage, ElLoading } from 'element-plus';
import { nextTick } from 'vue';
// 导入静态资源
import userAvatarImg from '@/assets/images/profile.jpg';
import aiAvatarImg from '@/assets/logo/logo.png';

export default {
  name: 'MarkDetail',
  components: {
    QuillEditor
  },
  data() {
    return {
      loading: false,
      answerId: '',
      student: {
        studentId: '',
        studentName: '',
        submitTime: '',
        examTime: '',
        totalScore: 0
      },
      paper: {
        paperName: '',
        totalScore: 0
      },
      questionList: [],
      remark: '',
      totalScore: 0,
      // 富文本编辑器配置
      editorOptions: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'script': 'sub' }, { 'script': 'super' }],
            [{ 'indent': '-1' }, { 'indent': '+1' }],
            [{ 'direction': 'rtl' }],
            [{ 'size': ['small', false, 'large', 'huge'] }],
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            [{ 'color': [] }, { 'background': [] }],
            [{ 'font': [] }],
            [{ 'align': [] }],
            ['clean'],
            ['link', 'image']
          ]
        },
        placeholder: '请在此输入评语...'
      },
      aiAssistDialogVisible: false,
      aiLoading: false,
      aiChatInput: "",
      aiChatHistory: [],
      apiTestLoading: false,
      aiCache: new Map(), // 用于缓存AI辅助批阅结果
      currentQuestion: null,
      userAvatar: userAvatarImg,
      aiAvatar: aiAvatarImg,
    }
  },
  computed: {
    // 所有题目
    allQuestions() {
      return this.questionList || [];
    },
    // 分类后的题目
    singleChoiceQuestions() {
      return this.questionList.filter(q => q.question_type === 0);
    },
    multiChoiceQuestions() {
      return this.questionList.filter(q => q.question_type === 1);
    },
    judgmentQuestions() {
      return this.questionList.filter(q => q.question_type === 2);
    },
    fillBlankQuestions() {
      return this.questionList.filter(q => q.question_type === 3);
    },
    essayQuestions() {
      return this.questionList.filter(q => q.question_type === 4);
    }
  },
  created() {
    this.answerId = this.$route.params.answerId;
    // 从answerId解析paperId (studentId_paperId)
    const parts = this.answerId.split('_');
    if (parts.length === 2) {
      this.paperId = parts[1];
      this.loadPaperInfo();
    }
    this.getDetail();
    
    // 加载MathJax
    this.loadMathJax();
  },
  mounted() {
    // 在元素挂载后初始化MathJax
    this.$nextTick(() => {
      setTimeout(() => {
        this.initMathJax();
      }, 300);
    });
  },
  updated() {
    // 在组件更新后重新渲染数学公式
    this.$nextTick(() => {
      setTimeout(() => {
        this.initMathJax();
      }, 200);
    });
  },
  methods: {
    // 加载MathJax脚本
    loadMathJax() {
      if (window.MathJax) {
        console.log('MathJax已加载:', window.MathJax.version);
        this.initMathJax();
        return;
      }

      console.log('正在加载MathJax...');
      // 先设置MathJax配置
      window.MathJax = {
        tex: {
          inlineMath: [['$', '$'], ['\\(', '\\)']],
          displayMath: [['$$', '$$'], ['\\[', '\\]']],
          processEscapes: true
        },
        svg: {
          fontCache: 'global'
        },
        options: {
          enableMenu: false,
          menuOptions: {
            settings: {
              assistiveMml: false,
              collapsible: false,
              explorer: false
            }
          }
        }
      };

      // 然后加载MathJax脚本
      const script = document.createElement('script');
      script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js';
      script.async = true;
      script.id = 'MathJax-script';
      script.onload = () => {
        console.log('MathJax脚本加载完成');
        setTimeout(() => {
          this.initMathJax();
        }, 100);
      };
      document.head.appendChild(script);
    },

    // 初始化MathJax
    initMathJax() {
      if (!window.MathJax) {
        console.warn('MathJax尚未加载');
        return;
      }

      console.log('尝试渲染数学公式...');
      try {
        // 兼容不同版本的MathJax
        if (typeof window.MathJax.typesetPromise === 'function') {
          window.MathJax.typesetPromise()
            .then(() => console.log('MathJax.typesetPromise渲染成功'))
            .catch(err => console.error('MathJax渲染失败:', err));
        } else if (typeof window.MathJax.typeset === 'function') {
          window.MathJax.typeset();
          console.log('MathJax.typeset渲染成功');
        } else if (window.MathJax.Hub && typeof window.MathJax.Hub.Queue === 'function') {
          window.MathJax.Hub.Queue(["Typeset", window.MathJax.Hub]);
          console.log('MathJax.Hub.Queue渲染成功');
        } else {
          console.warn('找不到合适的MathJax渲染方法');
        }
      } catch (error) {
        console.error('MathJax渲染出错:', error);
      }
    },
    
    // 获取试卷信息
    loadPaperInfo() {
      getPaperForExam(this.paperId, false).then(response => {
        if (response && response.data) {
          this.paper = response.data;
        }
      }).catch(error => {
        console.log('获取试卷信息失败',error);
      });
    },
    
    // 渲染数学公式
    renderMathFormula(content) {
      if (!content) return '';
      
      // 替换图片链接
      content = content.replace(/\[img\](.*?)\[\/img\]/g, '<img src="$1" style="max-width:100%;">');
      
      // 处理数学公式，确保正确显示
      // 判断是否已经是HTML内容，避免重复处理
      if (content.indexOf('<') === -1 || content.indexOf('>') === -1) {
        // 特别处理"或"关系，防止它被误认为是数学公式的一部分
        if (content.includes('或')) {
          const parts = content.split('或');
          for (let i = 0; i < parts.length; i++) {
            parts[i] = parts[i].trim();
          }
          content = parts.join(' 或 ');
        }
      }
      
      return content;
    },
    
    // 获取答卷详情
    getDetail() {
      this.loading = true;
      getAnswerDetail(this.answerId).then(response => {
        if (response.data && response.data.length > 0) {
          console.log('答卷详情数据:', response.data);
          
          const firstItem = response.data[0];
          // 从answerId中解析出学生ID，格式为：studentId_paperId
          const studentId = this.answerId.split('_')[0];
          
          // 更新学生基本信息
          this.student = {
            studentId: studentId,
            studentName: firstItem.student_name || '未知',
            submitTime: firstItem.submit_time || '-',
            examTime: firstItem.exam_time || '-',
            totalScore: firstItem.paper_total_score || 0
          };
          
          // 通过学号获取学生详细信息
          this.getStudentInfo(studentId);
          
          this.paper.paperName = firstItem.paper_name || '试卷批阅';
          this.paper.totalScore = firstItem.paper_total_score || 0;
          
          // 处理问题列表
          this.questionList = response.data.map(item => {
            // 渲染题目内容数学公式
            const questionContent = this.renderMathFormula(item.question_content);
            
            // 为多选题创建选项数组
            const selectedOptions = [];
            if (item.question_type == 1 && item.student_answer) {
              const answers = item.student_answer.split(',');
              const options = this.parseOptions(item.options);
              
              // 初始化选项选中状态
              options.forEach(option => {
                selectedOptions.push(answers.includes(option.value));
              });
            }
            
            // 处理判断题答案格式
            let processedStudentAnswer = item.student_answer;
            if (item.question_type === 2 && item.student_answer) {
              // 判断题答案可能是A/B或1/0或true/false格式，需要标准化
              processedStudentAnswer = this.standardizeJudgmentAnswer(item.student_answer);
            }
            
            // 处理判断题正确答案格式
            let processedQuestionAnswer = item.question_answer;
            if (item.question_type === 2 && item.question_answer) {
              // 判断题正确答案也需要标准化
              processedQuestionAnswer = this.standardizeJudgmentAnswer(item.question_answer);
            }
            
            // 确保分数在有效范围内
            const studentScore = parseFloat(item.student_score || 0);
            const questionScore = parseFloat(item.question_score || 0);
            const finalStudentScore = Math.min(Math.max(0, studentScore), questionScore).toFixed(1);
            
            // 确保is_correct的判断与得分一致 - 只有满分才算对
            const isCorrect = studentScore === questionScore;
            
            return {
              ...item,
              question_content: questionContent,
              is_correct: isCorrect,
              student_score: finalStudentScore,
              question_score: questionScore.toFixed(1),
              selectedOptions: selectedOptions,
              student_answer: processedStudentAnswer,
              question_answer: processedQuestionAnswer
            };
          });
          
          this.remark = firstItem.remark || '';
          
          this.loading = false;
          
          // 在数据加载完成后渲染数学公式
          this.$nextTick(() => {
            setTimeout(() => {
              this.initMathJax();
            }, 300); // 给一定的延迟确保DOM已经更新
          });
        } else {
          this.$message.error('获取答卷详情失败');
          this.loading = false;
        }
      }).catch(error => {
        console.error('获取答卷详情失败:', error);
        this.$message.error('获取答卷详情失败');
        this.loading = false;
      });
    },
    
    // 解析选项
    parseOptions(optionsString) {
      if (!optionsString) return [];
      
      return optionsString.split('|').map(opt => {
        // 查找第一个点的位置作为标签分隔符
        const dotIndex = opt.indexOf('.');
        if (dotIndex === -1) return { label: '', content: opt, value: '' };
        
        const label = opt.substring(0, dotIndex);
        // 保留内容的完整格式，不做额外处理
        const content = opt.substring(dotIndex + 1);
        
        return {
          label: label,
          content: content,
          value: label
        };
      });
    },

    // 检查选项是否被选中
    isOptionSelected(question, optionValue) {
      if (!question.student_answer) return false;
      return question.student_answer.split(',').includes(optionValue);
    },
    
    // 获取题型名称
    getQuestionTypeName(type) {
      const typeMap = {
        0: "单选题",
        1: "多选题",
        2: "判断题",
        3: "填空题",
        4: "简答题"
      };
      return typeMap[type] || "未知类型";
    },
    
    // 格式化学生答案
    formatStudentAnswer(question) {
      if (!question.student_answer) return '(未作答)';
      
      if (question.question_type === 0) {
        return question.student_answer;
      } else if (question.question_type === 1) {
        return question.student_answer;
      } else if (question.question_type === 3) {
        // 填空题答案不做特殊处理，保持原样
        return question.student_answer;
      } else {
        return question.student_answer;
      }
    },
    
    // 格式化正确答案
    formatCorrectAnswer(question) {
      if (!question.question_answer) return '(无答案)';
      
      if (question.question_type === 0) {
        return this.formatSingleChoiceAnswer(question.question_answer);
      } else if (question.question_type === 1) {
        return this.formatMultipleChoiceAnswer(question.question_answer);
      } else if (question.question_type === 2) {
        return this.formatJudgmentAnswer(question.question_answer);
      } else if (question.question_type === 3) {
        // 填空题答案直接使用formatFillAnswer方法处理
        return this.formatFillAnswer(question.options);
      } else {
        return question.question_answer;
      }
    },
    
    // 格式化单选题答案
    formatSingleChoiceAnswer(answer) {
      return answer || '';
    },
    
    // 格式化多选题答案
    formatMultipleChoiceAnswer(answer) {
      return answer || '';
    },
    
    // 格式化判断题答案
    formatJudgmentAnswer(answer) {
      if (!answer) return '';
      
      // 支持多种格式：1/0, A/B, true/false
      if (answer === '1' || answer === 'A' || answer === 'true') {
        return '正确';
      } else {
        return '错误';
      }
    },
    
    // 格式化填空题学生答案
    formatFillBlankAnswer(answer) {
      if (!answer) return '(未作答)';
      // 只处理HTML特殊字符，不替换逗号为分号
      return answer.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    },
    
    // 格式化填空题正确答案
    formatFillAnswer(optionsString) {
      if (!optionsString) return '(无答案)';
      
      // 直接显示后端已处理好的选项字符串，确保MathJax正确渲染
      this.$nextTick(() => {
        setTimeout(() => {
          this.initMathJax();
        }, 100);
      });
      
      return optionsString;
    },
    
    // 获取分数样式类
    getScoreClass(score, totalScore) {
      if (!score || !totalScore) return 'score-fail';
      
      const percentage = (parseFloat(score) / parseFloat(totalScore)) * 100;
      
      if (percentage >= 90) {
        return 'score-excellent';
      } else if (percentage >= 80) {
        return 'score-good';
      } else if (percentage >= 60) {
        return 'score-pass';
      } else {
        return 'score-fail';
      }
    },
    
    // 获取题型总分
    getSectionScore(questions) {
      return questions.reduce((sum, q) => sum + parseFloat(q.question_score || 0), 0);
    },
    
    // 减少分数
    decreaseScore(question) {
      const score = parseFloat(question.student_score);
      if (score >= 0.5) {
        question.student_score = (score - 0.5).toFixed(1);
        this.updateScoreStatus(question);
      }
    },
    
    // 增加分数
    increaseScore(question) {
      const score = parseFloat(question.student_score);
      const maxScore = parseFloat(question.question_score);
      if (score < maxScore) {
        question.student_score = Math.min(maxScore, score + 0.5).toFixed(1);
        this.updateScoreStatus(question);
      }
    },
    
    // 验证分数输入
    validateScoreInput(val, question) {
      // 不允许空值或非数字
      if (val === '' || isNaN(parseFloat(val))) {
        this.$message.warning('请输入有效的分数值');
        question.student_score = '0.0';
        return false;
      }
      
      const score = parseFloat(val);
      const maxScore = parseFloat(question.question_score);
      
      // 检查范围
      if (score < 0) {
        this.$message.warning('分数不能小于0');
        question.student_score = '0.0';
        return false;
      }
      
      if (score > maxScore) {
        this.$message.warning(`分数不能超过题目满分${maxScore}分`);
        question.student_score = maxScore.toFixed(1);
        return false;
      }
      
      return true;
    },
    
    // 更新分数状态
    updateScoreStatus(question) {
      // 首先验证输入
      if (!this.validateScoreInput(question.student_score, question)) {
        // 验证失败时已在validateScoreInput中设置了有效值
      }
      
      // 修改判断逻辑：只有得满分才算正确
      const score = parseFloat(question.student_score);
      const maxScore = parseFloat(question.question_score);
      question.is_correct = score === maxScore;
      
      // 确保格式统一为一位小数
      question.student_score = score.toFixed(1);
    },
    
    // 提交批阅
    submitMark() {
      // 提交前验证所有分数
      let hasInvalidScore = false;
      
      this.questionList.forEach(question => {
        if (!this.validateScoreInput(question.student_score, question)) {
          hasInvalidScore = true;
        }
        this.updateScoreStatus(question);
      });
      
      if (hasInvalidScore) {
        this.$message.error('存在无效的分数输入，请检查');
        return;
      }
      
      this.loading = true;
      
      const markData = {
        markData: this.questionList.map(item => {
          return {
            questionId: item.question_id,
            score: parseFloat(item.student_score),
            isCorrect: item.is_correct ? 1 : 0
          };
        }),
        remark: this.remark
      };
      
      markPaper(this.answerId, markData).then(response => {
        this.$message.success('批阅成功');
        this.loading = false;
        this.goBack();
      }).catch(error => {
        console.error('批阅失败:', error);
        this.$message.error('批阅失败');
        this.loading = false;
      });
    },
    
    // 返回
    goBack() {
      this.$router.push({ 
        name: 'MarkAnswers',
        params: { paperId: this.answerId.split('_')[1] }
      });
    },

    // 计算总分
    calculateTotalScore() {
      return this.questionList.reduce((sum, q) => sum + parseFloat(q.student_score || 0), 0);
    },

    // 格式化用时
    formatExamTime(examTime) {
      if (!examTime) return '-'
      
      // 如果已经是格式化好的字符串，如"3小时29分7秒"，直接返回
      if (typeof examTime === 'string' && (examTime.includes('小时') || examTime.includes('分') || examTime.includes('秒'))) {
        // 对于仅有分秒格式的，如果分钟过大(>=60)，转换为小时分钟格式
        if (!examTime.includes('小时') && examTime.includes('分')) {
          const minutesMatch = examTime.match(/(\d+)分/);
          if (minutesMatch && parseInt(minutesMatch[1]) >= 60) {
            const minutes = parseInt(minutesMatch[1]);
            const hours = Math.floor(minutes / 60);
            const remainingMinutes = minutes % 60;
            let result = hours + '小时';
            if (remainingMinutes > 0) {
              result += remainingMinutes + '分';
            }
            // 处理秒数
            const secondsMatch = examTime.match(/(\d+)秒/);
            if (secondsMatch) {
              result += secondsMatch[1] + '秒';
            }
            return result;
          }
        }
        return examTime;
      }
      
      // 如果是 HH:MM:SS 格式
      if (typeof examTime === 'string' && examTime.includes(':')) {
        const parts = examTime.split(':')
        if (parts.length === 3) {
          const hours = parseInt(parts[0])
          const minutes = parseInt(parts[1])
          const seconds = parseInt(parts[2])
          
          let result = ''
          if (hours > 0) {
            result += hours + '小时'
          }
          if (minutes > 0 || hours > 0) {
            result += minutes + '分'
          }
          result += seconds + '秒'
          
          return result
        }
      }
      
      return examTime
    },

    // 标准化判断题答案格式
    standardizeJudgmentAnswer(answer) {
      if (answer === 'A' || answer === 'true' || answer === '1') {
        return '1';
      } else if (answer === 'B' || answer === 'false' || answer === '0') {
        return '0';
      }
      return answer;
    },

    // 获取考试详情
    async getExamDetail() {
      try {
        const res = await getMarkExamDetail(this.markExamId);
        if (res.code === 200) {
          this.examData = res.data;
          // 在DOM更新后初始化MathJax
          this.$nextTick(() => {
            setTimeout(() => {
              if (window.MathJax) {
                window.MathJax.typesetPromise?.();
              }
            }, 100);
          });
        }
      } catch (error) {
        console.error(error);
      }
    },

    // 添加获取学生信息的方法
    getStudentInfo(studentId) {
      getStudentByNumber(studentId).then(response => {
        if (response.code === 200 && response.data) {
          this.student.studentName = response.data.studentName || response.data.student_name || this.student.studentName;
        } else {
          console.warn('获取学生信息失败:', response);
        }
      }).catch(error => {
        console.error('获取学生信息API失败:', error);
      });
    },

    // 打开AI辅助对话框
    openAIAssistDialog(question) {
      this.currentQuestion = question;
      this.aiAssistDialogVisible = true;
      
      // 每次打开对话框时管理缓存大小
      this.manageCacheSize();
      
      // 检查缓存中是否有该题目的AI批阅结果
      const cacheKey = `${question.question_id}-${this.student.studentId}`;
      if (this.aiCache.has(cacheKey)) {
        const cachedData = this.aiCache.get(cacheKey);
        if (cachedData.expiry > Date.now()) { // 检查缓存是否过期（5分钟）
          // 使用缓存数据
          question.aiMarkResult = cachedData.result;
          this.aiChatHistory = cachedData.chatHistory || [];
          return;
        } else {
          // 缓存已过期，删除
          this.aiCache.delete(cacheKey);
        }
      }
      
      // 如果没有缓存或缓存已过期，则清空聊天记录
      this.aiChatHistory = [];
    },
    
    // AI辅助批阅
    aiAssistMark(question) {
      if (!question || !question.student_answer || !question.question_answer) {
        this.$modal.msgError("学生答案或参考答案不能为空！");
        return;
      }
      
      this.aiLoading = true;
      
      // 准备数据
      const data = {
        questionScore: question.question_score || 10.0,
        questionContent: question.question_content || "",
        studentAnswer: question.student_answer || "",
        standardAnswer: question.question_answer || "",
        analysis: question.question_analysis || ""
      };
      
      // 调用API，启用图片处理
      assistMarkSubjectiveQuestion(data, true)
        .then(response => {
          if (response.code === 200) {
            const result = response.data;
            
            // 保存结果到题目
            question.aiMarkResult = result;
            
            // 处理内容，格式化AI回复
            const formattedContent = this.formatAIResponse(result.content);
            
            // 添加AI回复到聊天历史
            this.aiChatHistory.push({
              role: "assistant",
              content: formattedContent || "AI辅助批阅完成"
            });
            
            // 缓存结果，设置5分钟过期
            const cacheKey = `${question.question_id}-${this.student.studentId}`;
            this.aiCache.set(cacheKey, {
              result: result,
              chatHistory: [...this.aiChatHistory],
              expiry: Date.now() + 5 * 60 * 1000 // 5分钟后过期
            });
            
            this.$modal.msgSuccess("AI辅助批阅成功");
            
            // 滚动到底部
            this.scrollToBottom();
            
            // 使用nextTick确保数学公式能够正确渲染
            nextTick(() => {
              if (window.MathJax) {
                window.MathJax.typesetPromise && window.MathJax.typesetPromise();
              }
            });
          } else {
            this.$modal.msgError("AI辅助批阅失败: " + response.msg);
          }
        })
        .catch(error => {
          console.log("AI辅助批阅出错", error);
          this.$modal.msgError("AI辅助批阅出错: " + (error.message || "未知错误"));
        })
        .finally(() => {
          this.aiLoading = false;
        });
    },
    
    // 格式化AI回复内容
    formatAIResponse(content) {
      if (!content) return "";
      
      // 分割内容
      const parts = content.split('###');
      if (parts.length <= 1) return content;
      
      let formattedContent = parts[0]; // 保留第一部分
      
      // 处理剩余部分
      for (let i = 1; i < parts.length; i++) {
        const part = parts[i].trim();
        if (part) {
          // 提取标题和内容
          const titleMatch = part.match(/^([^\.]+?)(\s|$)/);
          let title = '';
          let text = part;
          
          if (titleMatch && titleMatch[1]) {
            title = titleMatch[1].trim();
            text = part.substring(titleMatch[0].length).trim();
          }
          
          // 第一个部分使用粗体标题，不换行
          if (i === 1) {
            formattedContent += `<strong>${title}</strong>: ${text}`;
          } else {
            // 其他部分增加换行并使用粗体标题
            formattedContent += `<br><br><strong>${title}</strong>: ${text}`;
          }
        }
      }
      
      return formattedContent;
    },
    
    // 应用AI建议的分数
    applyAIScore(question) {
      if (!question || !question.aiMarkResult || question.aiMarkResult.suggestedScore === undefined) {
        this.$modal.msgError("没有可用的AI建议分数");
        return;
      }
      
      // 获取AI建议的分数
      let score = question.aiMarkResult.suggestedScore;
      
      // 确保分数在有效范围内
      const maxScore = question.question_score || 10.0;
      if (score < 0) score = 0;
      if (score > maxScore) score = maxScore;
      
      // 更新题目的得分
      question.student_score = score;
      question.mark_status = 1; // 标记为已批阅
      
      this.$modal.msgSuccess(`已应用AI建议分数: ${score}分`);
    },
    
    // 发送聊天消息
    sendChatMessage() {
      // 检查是否有内容
      if (!this.aiChatInput.trim()) return;
      
      const userMessage = this.aiChatInput.trim();
      this.aiChatInput = "";
      
      // 添加用户消息到聊天历史
      this.aiChatHistory.push({
        role: "user",
        content: userMessage
      });
      
      this.aiLoading = true;
      
      // 准备历史消息数组，确保是字符串数组而不是对象数组
      // 后端API期望messages是String[]类型
      const messageHistory = this.aiChatHistory
        .filter(msg => msg.role !== "user" || this.aiChatHistory.indexOf(msg) < this.aiChatHistory.length - 1)
        .map(item => item.content);
      
      console.log("发送聊天请求，prompt:", userMessage, "历史消息:", messageHistory);
      
      // 调用API发送消息
      chatWithAI(userMessage, messageHistory)
        .then(response => {
          if (response.code === 200) {
            const result = response.data;
            console.log("收到AI回复:", result);
            
            // 格式化AI回复内容
            const formattedContent = this.formatAIResponse(result.content || "AI助手无法回复");
            
            // 添加AI回复到聊天历史
            this.aiChatHistory.push({
              role: "assistant",
              content: formattedContent
            });
            
            // 缓存更新后的聊天记录
            if (this.currentQuestion) {
              const cacheKey = `${this.currentQuestion.question_id}-${this.student.studentId}`;
              if (this.aiCache.has(cacheKey)) {
                const cachedData = this.aiCache.get(cacheKey);
                cachedData.chatHistory = [...this.aiChatHistory];
                cachedData.expiry = Date.now() + 5 * 60 * 1000; // 重置缓存时间
              }
            }
            
            // 滚动到底部
            this.scrollToBottom();
            
            // 渲染数学公式
            nextTick(() => {
              if (window.MathJax) {
                window.MathJax.typesetPromise && window.MathJax.typesetPromise();
              }
            });
          } else {
            this.$modal.msgError("发送消息失败: " + response.msg);
          }
        })
        .catch(error => {
          console.log("发送消息出错", error);
          this.$modal.msgError("发送消息出错: " + (error.message || "未知错误"));
        })
        .finally(() => {
          this.aiLoading = false;
        });
    },
    
    // 测试AI API连接
    testAIConnection() {
      this.apiTestLoading = true;
      
      testAIConnection()
        .then(response => {
          if (response.code === 200) {
            if (response.data.status === "success") {
              this.$modal.msgSuccess("AI API连接测试成功");
              
              // 添加系统消息到聊天历史
              this.aiChatHistory.push({
                role: "assistant",
                content: "AI API连接测试成功，您可以开始使用AI辅助批阅功能了。"
              });
              
              // 滚动到底部
              this.scrollToBottom();
            } else {
              this.$modal.msgError("AI API连接测试失败: " + response.data.error);
            }
          } else {
            this.$modal.msgError("API测试请求失败: " + response.msg);
          }
        })
        .catch(error => {
          console.log("API测试出错", error);
          this.$modal.msgError("API测试出错: " + (error.message || "未知错误"));
        })
        .finally(() => {
          this.apiTestLoading = false;
        });
    },
    
    // 滚动聊天记录到底部
    scrollToBottom() {
      nextTick(() => {
        if (this.$refs.chatHistoryRef) {
          const container = this.$refs.chatHistoryRef;
          container.scrollTop = container.scrollHeight;
        }
      });
    },
    
    // 修改现有按钮对应的方法，改为打开AI辅助对话框
    handleClickAiAssist(question) {
      this.openAIAssistDialog(question);
    },

    // 添加缓存管理方法
    manageCacheSize() {
      // 如果缓存项目超过50个，清理旧的缓存
      if (this.aiCache.size > 50) {
        // 转换为数组以便排序
        const cacheEntries = Array.from(this.aiCache.entries());
        
        // 根据过期时间排序
        cacheEntries.sort((a, b) => a[1].expiry - b[1].expiry);
        
        // 删除最早过期的25%的缓存
        const toRemove = Math.ceil(this.aiCache.size * 0.25);
        for (let i = 0; i < toRemove; i++) {
          if (cacheEntries[i]) {
            this.aiCache.delete(cacheEntries[i][0]);
          }
        }
        
        console.log(`已清理 ${toRemove} 个缓存项，当前缓存大小: ${this.aiCache.size}`);
      }
    },
  },
  watch: {
    // 监听问题列表变化，触发MathJax渲染
    questionList: {
      handler() {
        this.$nextTick(() => {
          setTimeout(() => {
            this.initMathJax();
          }, 300);
        });
      },
      deep: true
    }
  },
  beforeUnmount() {
    // 清理MathJax
    if (window.MathJax && window.MathJax.typesetClear) {
      window.MathJax.typesetClear();
    }
    
    // 有选择地清理AI辅助批阅缓存，只保留最近的10个项目
    if (this.aiCache.size > 10) {
      const cacheEntries = Array.from(this.aiCache.entries());
      cacheEntries.sort((a, b) => b[1].expiry - a[1].expiry);
      
      // 保留最近的10个缓存项
      this.aiCache.clear();
      for (let i = 0; i < Math.min(10, cacheEntries.length); i++) {
        this.aiCache.set(cacheEntries[i][0], cacheEntries[i][1]);
      }
    }
  }
};
</script>

<style>
/* 滚动条样式 - 全局适用 */
.ai-result-container::-webkit-scrollbar,
.ai-analysis-content::-webkit-scrollbar,
.ai-chat-history::-webkit-scrollbar {
  width: 6px;
}

.ai-result-container::-webkit-scrollbar-thumb,
.ai-analysis-content::-webkit-scrollbar-thumb,
.ai-chat-history::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.ai-result-container::-webkit-scrollbar-track,
.ai-analysis-content::-webkit-scrollbar-track,
.ai-chat-history::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}
</style>

<style scoped>
.app-container {
  padding: 20px;
}

.paper-info {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.paper-title {
  font-size: 24px;
  margin-bottom: 15px;
  text-align: center;
}

.paper-metadata {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  margin-bottom: 10px;
}

.metadata-item {
  margin: 5px 10px;
  font-size: 14px;
}

.score-value {
  font-weight: bold;
}

.paper-content {
  margin-bottom: 20px;
}

.question-section {
  margin-bottom: 30px;
}

.section-title {
  padding: 10px;
  background-color: #ecf5ff;
  border-left: 5px solid #409EFF;
  margin-bottom: 20px;
  font-weight: bold;
}

.question-item {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fff;
  box-sizing: border-box;
}

.error-question {
  border: 2px solid #F56C6C;
  padding: 19px;
}

.question-content {
  margin-bottom: 15px;
}

.question-title {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.question-index {
  margin-right: 5px;
  font-weight: bold;
}

.question-type {
  margin-right: 10px;
  color: #409EFF;
}

.question-score {
  margin-left: 10px;
  color: #303133;
}

.question-score-display {
  margin-left: auto;
  font-weight: bold;
}

.score-separator {
  margin: 0 4px;
  color: #909399;
}

.score-full {
  color: #67C23A;
}

.score-partial {
  color: #F56C6C;
}

.total-score {
  color: #303133;
}

.question-text {
  margin-bottom: 15px;
}

.options-container {
  margin-bottom: 20px;
}

.options-list {
  padding-left: 20px;
}

.option-item {
  margin-bottom: 10px;
  display: flex;
  align-items: flex-start;
}

.option-radio,
.option-checkbox {
  width: 100%;
}

.option-key {
  font-weight: bold;
  margin-right: 8px;
  flex-shrink: 0;
}

.option-content {
  display: inline-block;
}

.answer-area {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9fafc;
  border-radius: 4px;
}

.student-answer,
.correct-answer {
  margin-bottom: 15px;
}

.answer-label {
  font-weight: bold;
  margin-bottom: 5px;
  color: #606266;
}

.answer-content {
  padding: 10px;
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.mathjax-content {
  line-height: 1.6;
  white-space: pre-line; /* 保留换行 */
}

.score-control {
  display: flex;
  align-items: center;
  margin-top: 15px;
  flex-wrap: nowrap; /* 防止换行 */
}

.score-label {
  margin-right: 15px;
  font-weight: bold;
  white-space: nowrap; /* 防止文本换行 */
}

.input-group {
  display: flex;
  align-items: center;
  margin-right: 10px; /* 为右侧按钮留出空间 */
}

.score-input {
  width: 80px;
  text-align: center;
}

.remark-area {
  margin-top: 30px;
  margin-bottom: 30px;
}

.remark-label {
  font-weight: bold;
  margin-bottom: 10px;
}

.submit-area {
  text-align: center;
  margin-top: 30px;
}

.score-excellent {
  color: #67c23a;
}

.score-good {
  color: #409eff;
}

.score-pass {
  color: #303133;
}

.score-fail {
  color: #f56c6c;
}

.ai-mark-result {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9fafc;
  border-radius: 4px;
}

.ai-mark-title {
  font-weight: bold;
  margin-bottom: 10px;
  font-size: 18px;
  color: #409EFF;
}

.ai-mark-content {
  margin-bottom: 10px;
}

.ai-mark-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.ai-score-label {
  font-weight: bold;
}

.ai-score-value {
  font-weight: bold;
  color: #67C23A;
}

/* AI辅助批阅对话框样式 */
.ai-assist-dialog {
  display: flex;
  flex-direction: column;
  height: 600px;
}

.ai-result-container {
  padding: 15px;
  border-bottom: 1px solid #eee;
  max-height: 350px;
  overflow-y: auto;
}

.ai-result-content {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

.ai-analysis {
  flex: 3;
}

.ai-analysis h3 {
  margin-top: 0;
  color: #409EFF;
  font-size: 18px;
  font-weight: bold;
}

.ai-analysis-content {
  background: #f9f9f9;
  padding: 10px;
  border-radius: 4px;
  max-height: 280px;
  overflow-y: auto;
}

.ai-score {
  flex: 1;
  text-align: center;
}

.ai-score h3 {
  margin-top: 0;
  color: #409EFF;
  font-size: 18px;
  font-weight: bold;
}

.ai-score-value {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0;
  color: #67C23A;
}

.ai-empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 250px;
}

.ai-chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.ai-chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.ai-chat-message {
  display: flex;
  margin-bottom: 15px;
  justify-content: flex-start;
}

.ai-chat-content {
  max-width: 80%;
}

.ai-chat-text {
  padding: 10px;
  border-radius: 4px;
  word-break: break-word;
}

.ai-chat-message.user {
  justify-content: flex-end;
}

.ai-chat-message.user .ai-chat-content .ai-chat-text {
  background-color: #ecf5ff;
  color: #303133;
  border: 1px solid #d9ecff;
}

.ai-chat-message.assistant {
  justify-content: flex-start;
}

.ai-chat-message.assistant .ai-chat-content .ai-chat-text {
  background-color: #f0f9eb;
  color: #303133;
  border: 1px solid #e1f3d8;
}

.ai-chat-input {
  padding: 15px;
  border-top: 1px solid #eee;
}

.ai-chat-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  gap: 10px;
}

/* AI辅助批阅按钮样式 */
.ai-assist-btn {
  margin-left: auto; /* 使按钮靠右对齐 */
}
</style>

